﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MrcWeb.Controllers;
using Microsoft.AspNetCore.Mvc;
using Mrc.Entity;
using Mrc.Application;
using DotNetEx;
using Mrc.Application.Helper;
using Mrc.Data;
namespace Mrc.Web.Areas.Admin.Controllers
{
    [Area("Admin")]
    [Permission("system.dbback")]
    public class DataBaseController : BaseController
    {
        private readonly ISysDBBackupService _sysDBBackupService;
        public DataBaseController(ISysDBBackupService sysDBBackupService)
        {
            this._sysDBBackupService = sysDBBackupService;
        }
        #region  View
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Clear()
        {
            return View();
        }

        [Permission("system.dbback.add")]
        public ActionResult Add()
        {
            return View();
        }
        [Permission("system.dbback.update")]
        public ActionResult Update(string id)
        {
            return View(_sysDBBackupService.Single(id));
        }
        #endregion

        #region Data
        public async Task<JsonResult> Models(int pageNumber, int pageSize)
        {
            return Json(await Task.Run(()=> {
                LayuiTableJson<SysDBBackuModels> layuiTableJson = new LayuiTableJson<SysDBBackuModels>();
                var dbContext = DbContextHelper.GetDBContext();
                var query = dbContext.Query<SysDBBackup>().AdminFilter(CurrentSession, x => x.CreateUserId == CurrentSession.UserId);
                layuiTableJson.count = query.Count();
                var data = query.Skip((pageNumber - 1) * pageSize).Take(pageSize).InnerJoin<SysUser>((back, user) => back.CreateUserId == user.Id).Select((back, user) => new SysDBBackuModels
                {
                    Id=back.Id,
                    CreateName = user.Name,
                    Name = back.Name,
                    Description = back.Description,
                    RestoreTimes = back.RestoreTimes,
                    Size = back.Size,
                    CreateTime=back.CreateTime
                }).ToList();
                layuiTableJson.code = 0;
                layuiTableJson.msg = "";
                layuiTableJson.data = data;
                return layuiTableJson;
            }));     
        }
        #endregion

        #region API
        [Permission("system.dbback.add")]
        [HttpPost]
        public async Task<JsonResult> Add(string Name = "",string Description="")
        {
            var back = await Task.Run(() => DBBackHelper.DBBack());
            if(!Name.IsNullOrEmpty()) back.Name = Name;
            if(!Description.IsNullOrEmpty()) back.Description = Description;
            _sysDBBackupService.AddDBBack(back, CurrentSession);
            return Json(AjaxResult.CreateResult("添加成功"));
        }
        [Permission("system.dbback.update")]
        [HttpPost]
        public ActionResult Update(UpdateSysDBBackupDto dto)
        {
            _sysDBBackupService.UpdateDBBack(dto,CurrentSession);
            return Json(AjaxResult.CreateResult("更新成功"));
        }

        [Permission("system.dbback.restore")]
        [HttpPost]
        public async Task<JsonResult> Restore(string id)
        {
            var key = GlobalsConfig.Configuration["Key:DBBackKey"];
            var back = _sysDBBackupService.Single(id);
            string path = EncryptHelper.DesDecrypt(back.Path, key);
            await Task.Run(() => DBBackHelper.RestoreDatabase(path));
            return Json(AjaxResult.CreateResult("恢复成功"));
        }

        public JsonResult getPath(string id)
        {
            var key = GlobalsConfig.Configuration["Key:DBBackKey"];      
            var back = _sysDBBackupService.Single(id);
            string path =EncryptHelper.DesDecrypt(back.Path, key);
            return Json(path);
        }

        public async Task<JsonResult> GetAllTable()
        {
            List<string> sysTable = new List<string> { "IISKeyWords", "SysOrg", "SysOrgType", "SysPost", "SysRole", "SysUser", "SysUserLogOn","SysUserOrg", "SysDBBackup"};
            var back = await Task.Run(() => DBBackHelper.GetAllTables());
            var result = back.Except(sysTable).Select(x => new TableTemp { Name = x }).ToList();
            
            LayuiTableJson<TableTemp> layuiTableJson = new LayuiTableJson<TableTemp>();
            layuiTableJson.count = result.Count();
            layuiTableJson.code = 0;
            layuiTableJson.msg = "";
            layuiTableJson.data =result;
            return Json(layuiTableJson);
        }
        [Permission("system.dbback.clear")]
        [HttpPost]
        public async Task<JsonResult> ClearTables(string[] tables)
        {
            var result=await Task.Run(() => DBBackHelper.ClearTables(tables.ToList()));
            return Json(AjaxResult.CreateResult<List<string>>(ResultStatus.OK,$"已清除{string.Join("|", result)}",result));
        }      
        #endregion
    }
    public class TableTemp
    {
        public string Name { get; set; }
    }
}